﻿<?php
// 记录调试日志
$rawInput = file_get_contents('php://input');
$logData = date('Y-m-d H:i:s') . "\n" .
           "原始请求: " . $rawInput . "\n" .
           "客户端IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . "\n\n";
file_put_contents('request_log.txt', $logData, FILE_APPEND);

// 数据库配置
$host = 'localhost';
$db   = 'host_registry';
$user = 'root';
$pass = 'root';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => '数据库连接失败: ' . $e->getMessage()]);
    exit;
}

// 获取JSON数据
$data = json_decode($rawInput, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(['error' => '无效的JSON格式']);
    exit;
}

// 验证必填字段（新增mac验证）
$required = ['hostname', 'mac'];
foreach ($required as $field) {
    if (empty($data[$field])) {
        http_response_code(400);
        echo json_encode(['error' => "缺少必填字段: $field"]);
        exit;
    }
}

// 提取数据
$hostname = $data['hostname'];
$os = $data['os'] ?? 'unknown';
$ip = $data['ip'] ?? 'unknown';
$mac = $data['mac']?? 'unknown';
$remote_ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

// 数据库操作：插入或更新（以mac为唯一标识，因为MAC地址唯一）
try {
    // 1. 先检查数据表是否有mac_address字段，没有则添加（首次运行自动创建）
   // $pdo->exec("ALTER TABLE hosts ADD COLUMN IF NOT EXISTS mac_address VARCHAR(50) UNIQUE");
    
    // 2. 插入或更新数据
    $sql = "INSERT INTO hosts (
                hostname, os, local_ip, remote_ip, mac_address, last_seen
            ) VALUES (
                :hostname, :os, :local_ip, :remote_ip, :mac, CURRENT_TIMESTAMP
            ) ON DUPLICATE KEY UPDATE 
                hostname = VALUES(hostname),
                os = VALUES(os),
                local_ip = VALUES(local_ip),
                remote_ip = VALUES(remote_ip),
                last_seen = CURRENT_TIMESTAMP";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':hostname' => $hostname,
        ':os'       => $os,
        ':local_ip' => $ip,
        ':remote_ip'=> $remote_ip,
        ':mac'      => $mac
    ]);

    echo json_encode(['status' => 'ok', 'message' => '数据已更新']);
} catch (\PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => '数据库操作失败: ' . $e->getMessage()]);
    exit;
}
?>